import $ from 'jquery';
import { encryptToHT } from './common';
import { nameConfig } from '@theme/vm';

const SITE_ID = process.env.SITE_ID || '';

const xApiXXX = encryptToHT(new Date().getTime() + '', {
  key: '8aUNeWV2Iei11n44',
  iv: 'z6XnsL4bGvtf3o45',
});

const headers = {
  // 客户端类型，如果是APP，则使用app的设备类型
  'TB-CLIENT-TYPE': 'h5',
  'TB-VERSION': 'v1.0.0',
  'X-API-SITE': SITE_ID,
  'Content-Type': 'application/json; charset=utf-8',
  'X-API-XXX': xApiXXX,
  'Site-Code': nameConfig.siteCode,
};

export default function request({
  url,
  params,
  callback,
  fail,
  method = 'post',
}) {
  const _headers = {
    ...headers,
  };

  const options = {
    url,
    method,
    headers: _headers,
    body: JSON.stringify(params),
  };
  if (method === 'get') {
    delete options.body;
  }

  $.ajax({
    ...options,
    data: options.body,
    success: (res) => {
      const response = res;
      if (callback) {
        callback(response);
      }
    },
    error: (err) => {
      console.log(err);
      if (fail) {
        fail(err);
      }
    },
  });
}
